﻿using System.Web.Mvc;
using System.Threading.Tasks;
using System.Diagnostics;
using Beeldbankmvc.Models;

namespace Beeldbankmvc.Controllers
{
    public class MaintenanceController : Controller
    {
        string PhysicalWebPath = "";
        MaintenanceRepository maintenanceRepository = new MaintenanceRepository();

        public ActionResult Index()
        {
            MaintenanceModel maintenanceModel = new MaintenanceModel();
            maintenanceModel.SQL = "select top 1 from beeldbank_mediaobject order by id desc;";

            return View(maintenanceModel);
        }

        [HttpPost]
        [ValidateInput(true)]
        public ActionResult Index(FormCollection collection)
        {
            MaintenanceModel maintenanceModel = new MaintenanceModel();
            UpdateModel(maintenanceModel);
            maintenanceModel.Status = maintenanceRepository.ExecuteQuery(maintenanceModel.SQL);

            return View("Index", maintenanceModel);
        }

        public ActionResult CleanupErrors()
        {
            PhysicalWebPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
            
            var task = Task.Factory.StartNew(DoCleanup, TaskCreationOptions.LongRunning);

            MaintenanceModel maintenanceModel = new MaintenanceModel();
            maintenanceModel.Status = "Opruimen foutmeldingen gestart";

            return View("Index", maintenanceModel);
        }

        public void DoCleanup()
        {
            //long time operation   
            Process process = new Process
            {
                StartInfo =
                {
                    WorkingDirectory = PhysicalWebPath + "/Views/Maintenance",
                    FileName = "cleanuplog.bat",
                    CreateNoWindow = true
                }
            };
            process.Start();
            process.WaitForExit();
        }

        public ActionResult UpdateKeyWords()
        {
            MaintenanceModel maintenanceModel = new MaintenanceModel();
            
            try
            {
                KeyWordRepository keywordRepository = new KeyWordRepository();
                keywordRepository.UpdateStats("A1");
                maintenanceModel.Status = "Bijwerken trefwoord tellers gereed";
            }
            catch
            {
                maintenanceModel.Status = "Bijwerken trefwoord tellers mislukt";
            }
            
            return View("Index", maintenanceModel);
        }

    }
}
